package cc.rengu.redp.hawk.service.impl;

import cc.rengu.redp.hawk.algorithm.AverageInPeriod;
import cc.rengu.redp.hawk.algorithm.RateOfChange;
import cc.rengu.redp.hawk.domain.TimestampData;
import cc.rengu.redp.hawk.service.IndexAlgorithm;
import cc.rengu.redp.hawk.service.IndexArithmeticService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xushitang
 */
@Slf4j
@Service
public class IndexArithmeticServiceImpl implements IndexArithmeticService {

    private final static Map<String, IndexAlgorithm> indexAlgorithmMap = new HashMap<>();

    static {
        //算法注册
        indexAlgorithmMap.put(AverageInPeriod.class.getSimpleName(), new AverageInPeriod());
        indexAlgorithmMap.put(RateOfChange.class.getSimpleName(), new RateOfChange());
    }

    @Override
    public Float run(String algorithm, JSONObject algParams, JSONObject currData, Map<String, List<TimestampData>> indexesTimestampData) {
        IndexAlgorithm indexAlgorithm = indexAlgorithmMap.get(algorithm);
        if (indexAlgorithm == null) {
            log.error("algorithm:[{}] not found.", algorithm);
            return 0.0f;
        }

        return indexAlgorithm.run(algParams, indexesTimestampData, currData);
    }

    @Override
    public Map<String, IndexAlgorithm> getAlgorithmList() {
        return indexAlgorithmMap;
    }

    @Override
    public String getAlgorithmParamsSample(String algorithm) {
        IndexAlgorithm indexAlgorithm = indexAlgorithmMap.get(algorithm);
        if (indexAlgorithm != null) {
            return indexAlgorithm.paramsSample();
        } else {
            return "";
        }
    }
}
